package com.guohengspace.mq.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.asapi.ASClient;
import com.aliyun.openservices.ons.api.impl.authority.OnsAuthSigner;
import com.guohengspace.mq.common.ResponseResult;
import com.guohengspace.mq.model.query.EipBatchCreateParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Configuration(value = "mqUtil")
public class EipUtil {
    private static final Logger logger = LoggerFactory.getLogger(EipUtil.class);
    //Config config = new Config();
    @Autowired
    EipConfig eipConfig;
    public String combineContent(Map<String, String> params) {
        StringBuilder sb = new StringBuilder("");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getValue());
        }
        return sb.toString();
    }

    public String getTimeStamp(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(date.getTime());
    }
    public ResponseResult CallAliYunASCM(String action, String organizationId) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("Action", action);
        // parameters.put("RegionId", this.getRegionId());
        parameters.put("RegionId", eipConfig.getRegionId());
        parameters.put("Version", "2019-05-10");
        parameters.put("isFormat", false);
        try {
            // 创建ASClient连接。
            ASClient client = new ASClient();
            log.info("进入接口========");
            // 设置身份标识，标识调用来源，无实际作用，可随意设置，必填项。
            client.setSdkSource("admin");
            // 是否参数首字母大写转化。
            client.setIsFormat(false);
            // ASAPI的Endpoint地址
            //String endpoint = "https://public.asapi.cn-beijing-htbj-d01.res.bjcenter.ht-cloud.cn/asapi/v3";
            String endpoint = eipConfig.eipAsapiEndpoint;

            // 授权相关参数。
           parameters.put(ASClient.ACCESSKEY_ID, eipConfig.getAccessKeyId());
            parameters.put(ASClient.ACCESSKEY_SECRET, eipConfig.getAccessKeySecret());
            /*parameters.put(ASClient.ACCESSKEY_ID, "IecGCFszaYSlmVBc");
            parameters.put(ASClient.ACCESSKEY_SECRET, "BaIBEiGKMiVTsxXeSN8t0HYu2kUTzy");*/
            // 产品接口信息参数。
            parameters.put(ASClient.PRODUCT, "ascm");
            parameters.put(ASClient.ACTION, parameters.get("Action"));
            parameters.put(ASClient.VERSION, "2019-05-10");
            // 接口业务参数设置。
            if (action.equals("ListResourceGroupByOrgId")) {
                parameters.put("id", organizationId);
            }else {
                parameters.put("id", 1);
            }
            // 设置Headers。
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("x-acs-organizationid", "1");
            // 设置连接超时。
            // client.setConnectTimeout(10000);
            // 设置请求超时。
            // client.setSocketTimeout(10000);

            // 发起请求，并获取返回。
            log.info("endpoint:{},headers:{},parameters:{}", endpoint, headers, parameters);
            String result = client.doPost(endpoint, headers, parameters);
            log.info("ascm返回：{}", result);
            if (StringUtils.isBlank(result)) {
                return ResponseResult.ok(null);
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getString("code").equals("200")) {
                return ResponseResult.ok(jsonObject);
            } else {
                return ResponseResult.nok(jsonObject.getString("suggestion"));
            }
        } catch (Exception e) {
            log.error("ascmRequest异常: {}", e.getMessage(), e);
            return ResponseResult.nok(e.getMessage());
        }
    }

    public ResponseResult CallEIPAliYunASCM(String product, String action, EipBatchCreateParam eipBatchCreateParam, Map<String, String> params) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("Action", action);
        parameters.put("RegionId", eipBatchCreateParam.getRegionId());
        parameters.put("Version", "2016-04-28");
        parameters.put("isFormat", false);
        try {
            //Thread.sleep(2000);
            // 创建ASClient连接。
            ASClient client = new ASClient();
            log.info("进入接口========");
            // 设置身份标识，标识调用来源，无实际作用，可随意设置，必填项。
            client.setSdkSource("asapi-8958@asapi-inc.com");
            // 是否参数首字母大写转化。
            client.setIsFormat(false);
            // ASAPI的Endpoint地址
            String endpoint = eipConfig.eipAsapiEndpoint;

            /*parameters.put(ASClient.ACCESSKEY_ID, eipConfig.getAccessKeyId());
            parameters.put(ASClient.ACCESSKEY_SECRET, eipConfig.getAccessKeySecret());*/
            // 改为前端页面传过来的值
            parameters.put(ASClient.ACCESSKEY_ID, eipBatchCreateParam.getAccessKeyId());
            parameters.put(ASClient.ACCESSKEY_SECRET, eipBatchCreateParam.getAccessKeySecret());
            // 产品接口信息参数。
            parameters.put(ASClient.PRODUCT, product);
            parameters.put(ASClient.ACTION, parameters.get("Action"));
            parameters.put(ASClient.VERSION, parameters.get("Version"));
            // 接口业务参数设置。
            parameters.putAll(params);
            // 设置Headers。
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("x-acs-organizationid", eipBatchCreateParam.getDepartmentId());
            headers.put("x-acs-resourcegroupid", eipBatchCreateParam.getResourceGroupId());
            headers.put("x-acs-regionid", eipBatchCreateParam.getRegionId());
            // 设置连接超时。
            // client.setConnectTimeout(10000);
            // 设置请求超时。
            // client.setSocketTimeout(10000);

            // 发起请求，并获取返回。
            log.info("endpoint:{},headers:{},parameters:{}", endpoint, headers, parameters);

            String result = client.doPost(endpoint, headers, parameters);
            /*String result = "{\"asapiSuccess\":\"1\",\"AllocationId\":\"3333\",\"EipAddress\":\"192.168.11.252\",\"code\":\"200\"}";*/
            log.info("ascm返回：{}", result);
            if (StringUtils.isBlank(result)) {
                return ResponseResult.ok(null);
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getString("asapiSuccess").equals("true")) {
                return ResponseResult.ok(jsonObject);
            } else {
                return ResponseResult.nok(jsonObject.getString("suggestion"));
            }
        } catch (Exception e) {
            log.error("ascmRequest异常: {}", e.getMessage(), e);
            return ResponseResult.nok(e.getMessage());
        }
    }

    public static void main(String[] args) {
        EipUtil util = new EipUtil();
        /*String result = util.getRegionId();
        logger.info("result:{}", result);*/
        /*ResponseResult responseResult = util.CallAliYunASCM("GetOrganizationList");
        System.out.println("1111:" + responseResult.getData());*/
        ResponseResult responseResult = util.CallAliYunASCM("ListResourceGroup", null);
        System.out.println("1111:" + responseResult.getData());
    }
}
